package Thread.Safe;

/**
 * 观察多线程的安全问题
 */
public class ThreadSafeorUnsafe {
    public static class Counter{
        int count = 0;

         synchronized void increase()  {
         //在方法前添加synchronized关键字之后，以下的代码操作和属性都是原子性的和可见性的
             System.out.println(Thread.currentThread().getName()+"获取到锁~~");
             count++;
             try {
                 Thread.sleep(1000);
             } catch (InterruptedException e) {
                 throw new RuntimeException(e);
             }
         }
    }
    public static void main(String[] args) throws InterruptedException {
        Counter counter=new Counter();
        Thread t1=new Thread(()->{
            for (int i = 0; i <50000 ; i++) {
                counter.increase();
            }
        },"t1");
        Thread t2=new Thread(()->{
            for (int i = 0; i <50000 ; i++) {
                counter.increase();
            }
        },"t2");
        Counter counter1=new Counter();
        Thread t3=new Thread(()->{
            for (int i = 0; i <50000 ; i++) {
                counter1.increase();
            }
        },"t3");
        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();
        //主线程走到此处，t1和t2都已经执行结束，理性状态是count和等于1万
        System.out.println("t1和t2已经执行完毕~~");
        System.out.println(counter.count);
        System.out.println(counter1.count);
    }
}
